package com.itheima.tlias84.service.impl;

import com.itheima.tlias84.annotation.Log;
import com.itheima.tlias84.dto.SelectAllDeptDTO;
import com.itheima.tlias84.entity.Dept;
import com.itheima.tlias84.mapper.DeptMapper;
import com.itheima.tlias84.po.InsertDeptParam;
import com.itheima.tlias84.po.UpdateDeptParam;
import com.itheima.tlias84.service.DeptService;
import com.itheima.tlias84.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class DeptServiceImpl implements DeptService {

//    private final DeptMapper deptMapper;
//
////    @Autowired
//    public DeptServiceImpl(DeptMapper deptMapper) {
//        this.deptMapper = deptMapper;
//    }
    @Autowired
    DeptMapper deptMapper;

    @Override
    public List<SelectAllDeptDTO> selectAll() {
        int a = 1;
        if (a==1){
            throw  new ArithmeticException("发生了某些奇怪错误1");
        }

        return deptMapper.selectAll();

    }

    @Log
    @Override
    public int insertDept(InsertDeptParam param) {
        Dept dept = new Dept();
        dept.setName(param.getName());
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        return deptMapper.insertDept(dept);
    }

    @Log
    @Override
    public int deleteById(Integer id) {
        return deptMapper.deleteById(id);
    }

    @Override
    public UpdateDeptParam selectById(Integer id) {
        return deptMapper.selectById(id);
    }

    @Log
    @Override
    public ResultUtil updateById(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
//        Dept dept1 = deptMapper.selectByIdA(dept.getId());
//        List<SelectAllDeptDTO> selectAllDeptDTOS = deptMapper.selectAll();
//        List<String> list = selectAllDeptDTOS.stream().map(t -> t.name).toList();
//        if (list.contains(dept.getName())){
//            deptMapper.updateById(dept1);
//            return ResultUtil.fail("部门名修改异常");
//        }else {
//            deptMapper.updateById(dept);
//            return ResultUtil.success("修改成功");
//        }
        Dept dept1 = deptMapper.selectDeptByName(dept.getName());
        if (Objects.isNull(dept1)&& dept1.getId() !=dept.getId()){
            return ResultUtil.fail("部门名字错误");
        }
        deptMapper.updateById(dept);
        return ResultUtil.success();
    }

    @Override
    public int batchDelete(List<Integer> ids) {
        return deptMapper.batchDelete(ids);
    }
}
